package com.taichuan.selfcheck.ui.fragment;

import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.util.Pair;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.taichuan.finger.zaz.TcZazFingerClient;
import com.taichuan.finger.zaz.detect.FingerDetectRunnable;
import com.taichuan.finger.zaz.detect.FingerDetectStateListener;
import com.taichuan.keysupport.Key;
import com.taichuan.selfcheck.R;
import com.taichuan.selfcheck.config.PropertyDefaultValue;
import com.taichuan.selfcheck.hardware.LightControlUtils;
import com.taichuan.selfcheck.hardware.finger.FingerControlClient;
import com.taichuan.selfcheck.hardware.finger.FingerInitStateListener;
import com.taichuan.selfcheck.mvp.presenter.TestFingerPresenter;
import com.taichuan.selfcheck.mvp.viewinterface.FingerTestInterface;
import com.taichuan.selfcheck.ui.dialog.ResultDialog;
import com.taichuan.selfcheck.ui.fragment.base.AppBaseFragment;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 该类主要用于
 *
 * @author CamelLuo
 * @version 2021/2/1
 */
public class TestFingerFragment extends AppBaseFragment<FingerTestInterface, TestFingerPresenter> implements FingerTestInterface {
    private static final String TAG = TestFingerFragment.class.getSimpleName();

    private static final int MSG_REFRESH_FINGER_DETECT_INFO = 1;
    private static final int MSG_FINGER_DETECT_IMAGE = 2;
    private static final int MSG_REFRESH_INIT_INFO = 3;
    private static final int MSG_DISMISS_DIALOG = 4;

    @BindView(R.id.finger_test_info_textView)
    TextView infoTv;
    @BindView(R.id.finger_test_imageView)
    ImageView fingerIv;
    @BindView(R.id.finger_test_start_button)
    Button startBtn;
    private ResultDialog resultDialog;
    private ProgressDialog dialog;

    @Override
    protected int setContentViewId() {
        return R.layout.fragment_finger_test;
    }

    @Override
    protected void initView(View view, Bundle bundle) {
        //设置弹窗发送的事件——指纹测试
        resultDialog = new ResultDialog(PropertyDefaultValue.FUNCTION_TEST_19, getResources().getString(R.string.finger_test), getContext());

        if (!TcZazFingerClient.getInstance().isInit()){
            //监听指纹SDK初始化流程
            FingerControlClient.getInstance().setStateListener((isSuccess, stateReason) -> {
                Pair<Boolean, String> booleanStringPair = new Pair<Boolean, String>(isSuccess,stateReason);
                handler.sendMessage(handler.obtainMessage(MSG_REFRESH_INIT_INFO,booleanStringPair));
            });
            //初始化指纹SDK
            FingerControlClient.getInstance().initTcZazFingerClient(true);
        }


        startBtn.setTag("close");
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        //移除所有Handler消息事件
        handler.removeMessages(MSG_REFRESH_FINGER_DETECT_INFO);
        handler.removeMessages(MSG_FINGER_DETECT_IMAGE);
        handler.removeMessages(MSG_REFRESH_INIT_INFO);
        handler.removeMessages(MSG_DISMISS_DIALOG);

        //注销指纹SDK状态监听
        FingerControlClient.getInstance().setStateListener(null);
        //停止指纹探测线程
        TcZazFingerClient.getInstance().stopFingerDetectThread();
    }

    private final FingerDetectStateListener fingerDetectStateListener = new FingerDetectStateListener() {
        @Override
        public void refreshStateInfo(int stringId) {
            Log.e(TAG, "refreshStateInfo: 收到状态信息： " + getStrById(stringId));
            handler.sendMessage(handler.obtainMessage(MSG_REFRESH_FINGER_DETECT_INFO,stringId));
        }

        @Override
        public void showFingerImage(String filePath) {
            Log.e(TAG, "showFingerImage: 收到指纹数据图片： " + filePath);
            handler.sendMessage(handler.obtainMessage(MSG_FINGER_DETECT_IMAGE,filePath));
        }
    };

    private final Handler handler = new Handler(msg -> {
        switch (msg.what){
            case MSG_REFRESH_FINGER_DETECT_INFO:{
                int stringId = (int) msg.obj;
                if (stringId != 0){
                    infoTv.setText(getStrById(stringId));
                }
                break;
            }
            case MSG_FINGER_DETECT_IMAGE:{
                String filePath = (String) msg.obj;
                if (!TextUtils.isEmpty(filePath)){
                    //将图片路径转换为Bitmap
                    Bitmap bitmap = BitmapFactory.decodeFile(filePath, null);
                    if (bitmap != null){
                        fingerIv.setImageBitmap(bitmap);
                    }
                }
                break;
            }
            case MSG_REFRESH_INIT_INFO:{
                Pair<Boolean, String> resultPair = (Pair<Boolean, String>) msg.obj;
                if (resultPair != null){
                    boolean isSuccess = resultPair.first;
                    String reason = resultPair.second;
                    //打开Dialog,并展示内容
                    showStaticDialog(reason);

                    if (isSuccess){
                        if (dialog != null){
                            dialog.setCancelable(true);
                            dialog.setCanceledOnTouchOutside(true);
                        }
                        //延时1秒后关闭Dialog
                        dismissDialogDelayTime();
                    }
                }
                break;
            }
            case MSG_DISMISS_DIALOG:{
                dismissDialog();
                break;
            }
        }
        return false;
    });

    @OnClick({R.id.finger_test_start_button})
    @Override
    protected void onXmlClick(View v) {
        super.onXmlClick(v);
        switch (v.getId()){
            case R.id.finger_test_start_button:{
                //检测指纹SDK是否初始化成功
                if (TcZazFingerClient.getInstance().isInit()){
                    if (startBtn.getTag().equals("close")) {
                        //启动指纹探测线程
                        TcZazFingerClient.getInstance().startFingerDetectThread(fingerDetectStateListener);
                        startBtn.setTag("open");
                        startBtn.setText(getStrById(R.string.stop_finger_detect));
                    } else {
                        //停止指纹探测线程
                        TcZazFingerClient.getInstance().stopFingerDetectThread();
                        //清除状态信息和指纹图片
                        infoTv.setText("");
                        fingerIv.setImageResource(R.color.white);

                        startBtn.setTag("close");
                        startBtn.setText(getStrById(R.string.start_finger_detect));
                    }
                }else {
                    showMsg("指纹SDK未初始化成功，无法使用");
                }
                break;
            }
        }
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (dialog != null && dialog.isShowing()){
            showMsg("请等待指纹SDK初始化流程结束");
        }else {
            if (resultDialog.isShowing()) {
                resultDialog.dispatchKeyEvent(event);
            }
            if (event.getKeyCode() == Key.Convert.KEYCODE_1) {     //启动与停止指纹探测
                startBtn.performClick();
            }
        }
        return super.dispatchKeyEvent(event);
    }

    @Override
    protected boolean isAllowAutoFinishFragment() {
        return false;
    }

    @Override
    public void doOnAutoFinishFragment() {
        if (dialog != null && dialog.isShowing()){
            Log.e(TAG, "doOnAutoFinishFragment: 此时正在初始化指纹模块SDK，不允许执行页面退出");
        }else {
            resultDialog.show();
        }
    }

    @Override
    protected void getBundleValues(Bundle bundle) {

    }

    @Override
    protected TestFingerPresenter createPresenter() {
        return new TestFingerPresenter();
    }

    private void dismissDialogDelayTime(){
        if (handler != null){
            handler.sendEmptyMessageDelayed(MSG_DISMISS_DIALOG,1000);
        }
    }

    public void dismissDialog() {
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
    }

    public void showStaticDialog(String message) {
        if (dialog == null) {
            dialog = ProgressDialog.show(getActivity(),"",message,false,false);
            dialog.setCanceledOnTouchOutside(false);
        }
        if (!dialog.isShowing()) {
            dialog.show();
        }
        dialog.setMessage(message);
    }
}
